class Solution(object):
    def minSwaps(self, grid):
        m = len(grid)
        n = len(grid[0])
        p = [0] * n
        for i in range(m):
            right = n - 1
            while right >= 0:
                if grid[i][right] == 0:
                    right -= 1
                else:
                    break
            p[i] = n - 1 - right
        index = 0
        ans = 0
        while index < n - 1:
            right_index = index
            while right_index < n and p[right_index] < n - 1 - index:
                right_index += 1
            if right_index == n:
                return -1
            else:
                ans += right_index - index
                node = p[right_index]
                del p[right_index]
                p.insert(index, node)
                index += 1
        return ans